package com.javaee.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaee.entity.Location;
import com.javaee.entity.PageBean;
import com.javaee.entity.Test;
import com.javaee.entity.User;
import com.javaee.lucene.LuceneTest;
import com.javaee.service.TestService;
import com.javaee.service.UserService;
import com.javaee.util.PageUtil;
import com.javaee.util.ResultOutDto;
import com.javaee.util.StringUtil;

import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("/test")
public class TestController {

	@Resource
	private TestService testService;
	
	@Resource
	private UserService userService;
	
	@RequestMapping("/WebSocketView")
	public String goWebSocketView(){
		
		return "/test/webSocke";
	}
	
	/**
	 * 查询分页列表
	 * @return
	 */
	@RequestMapping("/TestList")
	public String getList(Model model,@RequestParam(value="page",required=false)String page,HttpServletRequest request){
		if(StringUtil.isEmpty(page)){
			page="1";
		}
		PageBean pageBean=new PageBean(Integer.parseInt(page),10);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Test> testList = testService.list(map);
		StringBuffer param=new StringBuffer();//查询参数
		model.addAttribute("testList",testList);
		model.addAttribute("pageCode",PageUtil.genPagination(request.getContextPath()+"/test/TestList.shtml", testService.getTotal(map), Integer.parseInt(page), 10, param.toString()));
		model.addAttribute("resultTotal",testList.size());
		return "/test/list";
	}
	
	@ResponseBody
	@RequestMapping("/getOneTest")
	public Object getOneTest(String id){
		Test test = testService.findById(id);
		return test;
	}
	
	/**
	 * 修改操作
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object updateTest(Test test) throws Exception{
		int status = testService.update(test);
		if(status==1){
			LuceneTest luceneTest = new LuceneTest();
			luceneTest.updateIndex(test);
		}
		return "success";
	}
	
	/**
	 * 新增操作
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String saveTest(Test test) throws Exception{
		int status = testService.add(test);
		if(status==1){
			LuceneTest luceneTest = new LuceneTest();
			luceneTest.addIndex(test); //新增索引
		}
		return "success";
	}
	
	/**
	 * 删除操作
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public String deleteTest(String id) throws Exception{
		int status = testService.delete(id);
		if(status==1){
			LuceneTest luceneTest = new LuceneTest();
			luceneTest.deleteIndex(id);
		}
		return "success";
	}
	
	
    @RequestMapping(value = "/testWebSocket", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8")  
    @ResponseBody  
    public String testWebSocket() throws IOException{ 
    	return "success";  
    }  
    
    @ResponseBody
    @RequestMapping(value="/getList",method=RequestMethod.GET)
    public ResultOutDto getList(){
    	HashMap<Object, Object> map = new HashMap<Object, Object>();
    	List<Test> list = testService.getList();
    	System.out.println(list);
    	map.put("data", list);
    	return ResultOutDto.ok(map);
    }
    
    /**
     * 检索索引
     * @param name
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/getByNameList")
    public List<Test> getByNameList(String name) throws Exception{
    	LuceneTest luceneTest = new LuceneTest();
    	List<Test> list = luceneTest.searchBlog(name.trim());
    	return list;
    }
    
   public static void main(String[] args) {
    	 //连接本地的 Redis 服务
        Jedis jedis = new Jedis("127.0.0.1",6379);
//        jedis.auth("root");
        System.out.println("连接成功");
        //查看服务是否运行
        System.out.println("服务正在运行: "+jedis.ping());
        
        //存储数据
        jedis.set("name", "小云龙");
        System.out.println("获取数据:"+jedis.get("name"));
        
        jedis.set("zhilagecai", "值啦个菜");
        System.out.println("值啦个菜"+jedis.get("zhilagecai"));
    	TestController controller = new TestController();
//    	controller.deleteFile("C:\\Users\\Lenovo\\Desktop\\新建文本文档.txt");
	}
    
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

  /*  public static void main(String[] args) {  
        //一维  
        List<Location> list = getChilds(data, 1);  
        for(Location l : list){  
            System.out.println(l.getName());  
        } 
        System.out.println("===============");
        
        //多维集合
        List<Location> locations= pushManyGroup(data,2);
        for (int i = 0; i < locations.size(); i++) {
			System.out.println("多维集合"+locations.get(i).getName());
			System.out.println("===================");
		}
        
        //多维  
        List<Location> list2 = getChildsManyGroup(data, 1);
        for (int i = 0; i < list2.size(); i++) {
			System.out.println("呵呵"+list2.get(i).getName());
			System.out.println("=================================");
		}
        for(Location l : list2){  
            System.out.println(l.getName());
            for(Location ll : l.getList()){  
                System.out.println("\t"+ll.getName());
                for(Location lll : ll.getList()){  
                    System.out.println("\t\t"+lll.getName());
                    for(Location lllL : lll.getList()){  
                        System.out.println("\t\t\t"+lllL.getName());  
                    }  
                } 
            }  
        }  
    }*/  
    
    
    //查询数据库表中所有数据,(这里模拟一个表的所有数据)  
    static List<Location> data = new ArrayList<Location>();    
    static{
        //new Location(编号, "名称", 父编号); 
        Location l = new Location();
        l.setId(1);
        l.setName("编程语言");
        l.setParentId(0);
        Location l1 = new Location();
        l1.setId(2);
        l1.setName("数据库");
        l1.setParentId(0);
        Location l2 = new Location();
        l2.setId(3);
        l2.setName("Java");
        l2.setParentId(1);
        Location l3 = new Location();
        l3.setId(4);
        l3.setName(".NET");
        l3.setParentId(1);
        Location l4 = new Location();
        l4.setId(5);
        l4.setName("java EE");
        l4.setParentId(3);
        Location l5 = new Location();
        l5.setId(6);
        l5.setName("java SE");
        l5.setParentId(3);
        Location l6 = new Location();
        l6.setId(7);
        l6.setName("java ME");
        l6.setParentId(3);
        Location l7 = new Location();
        l7.setId(8);
        l7.setName("asp.NET");
        l7.setParentId(4);
        Location l8 = new Location();
        l8.setId(9);
        l8.setName("ado.NET");
        l8.setParentId(4);
        Location l9 = new Location(); 
        l9.setId(10);
        l9.setName("MySQL");
        l9.setParentId(2);
        Location l10 = new Location();
        l10.setId(11);
        l10.setName("Oracle");
        l10.setParentId(2);
        Location l11 = new Location();
        l11.setId(12);
        l11.setName("hibernate");
        l11.setParentId(5);
        Location l12 = new Location();
        l12.setId(13);
        l12.setName("hibernate 3.5");
        l12.setParentId(12);
        Location l13 = new Location();
        l13.setId(14);
        l13.setName("hibernate 4.2");
        l13.setParentId(12);
        data.add(l);
        data.add(l1);
        data.add(l2);    
        data.add(l3);
        data.add(l9);
        data.add(l10);    
        data.add(l4);
        data.add(l5);
        data.add(l6);
        data.add(l7);
        data.add(l8);
        data.add(l11);  
        data.add(l12);
        data.add(l13);
    }   
    /**  
     * 根据id 获取所有父级目录 一维  
     * 用途（首页 > 编程语言 > JAVA >  hibernate > hibernate入门教程）类似这样的一个系统当前位置   传入位置获取到所有父级  
     * @param list  
     * @param pid  
     * @return  
     */ 
    public static List<Location> getParents(List<Location> list,int pid){    
        List<Location> arr = new ArrayList<Location>();   
        for (Location location : list) {    
            if(pid == location.getId()){    
                arr.addAll(getParents(list, location.getParentId()));    
                arr.add(location);  break;  
            }    
        }    
        return arr;    
    }    
    /** 
     * 根据id获取所有子集分类(一维List集合) 
     * 1 11 111 
     * @param list 
     * @param pid 
     * @return 
     */  
    public static List<Location> getChilds(List<Location> list,int pid){  
        List<Location> arr = new ArrayList<Location>();  
        for(Location location : list){  
            if(pid == location.getParentId()){  
                arr.addAll(getChilds(list, location.getId()));  
                arr.add(location);  
                  
            }  
        }  
        return arr;  
    }  
    /** 
     * 根据id返回所有子集分类,(多维List集合,List中含有子集List) 
     *  
     *  1 
     *    11 
     *       111 
     *  2 
     *    22 
     *       222  
     * @param list 
     * @param pid 
     * @return 
     */  
    public static List<Location> getChildsManyGroup(List<Location> list,int pid){  
        List<Location> arr = new ArrayList<Location>(); 
        for(Location location : list){  
            if(pid == location.getParentId()){
                location.setList(getChildsManyGroup(list, location.getId()));    
                arr.add(location);   
            }  
        }  
        return arr;  
    }  
        
    /**  
     * 组合为一维集合  
     * @param list  
     * @param pid  
     * @return  
     */    
    public static List<Location> pushOneGroup(List<Location> list,int pid){    
        List<Location> arr = new ArrayList<Location>();    
        for (Location location : list) {    
            if(pid == location.getParentId()){    
                arr.add(location);    
                arr.addAll(pushOneGroup(list, location.getId()));    
            }    
        }    
        return arr;    
    }    
    /**  
     * 组合为多维集合  
     * 用途：系统首页的导航菜单，常见的2-3级通过下面的方法压栈成多维集合在供前台显示  
     * @param list 要便利的集合数据  
     * @param pid  父id  
     * @return  
     */    
    public static List<Location> pushManyGroup(List<Location> list,int pid){    
        List<Location> arr = new ArrayList<Location>();    
        for (Location location : list) {    
            if(pid == location.getParentId()){    
                location.setList(pushManyGroup(list, location.getId()));    
                arr.add(location);    
            }    
        }    
        for (int i = 0; i < arr.size(); i++) {
			System.out.println("呵呵哒..."+arr.get(i).getName());
		}
        return arr;    
    }    
}
